package com.example.test.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.Selector;

/**
 * @Author: fxy
 * @Date: 2022/01/06/10:35
 * @Description:
 */
public class Demo1 {

    public static void main(String[] args) throws Exception {
        //read();
        write();
        //trans();
        //Selector
    }

    /**
     * FileChannel读取数据到buffer
     * @throws Exception
     */
    public static void read() throws Exception {
        String path = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\01.txt";
        RandomAccessFile aFile = new RandomAccessFile(path,"rw");
        FileChannel channel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(10);

        int bytesRead = channel.read(buf);
        while (bytesRead!=-1){
            System.out.println(bytesRead);
            buf.flip();
            while(buf.hasRemaining()){
                System.out.println((char)buf.get());
            }
            buf.clear();
            bytesRead = channel.read(buf);
        }
        aFile.close();
    }

    public static void write() throws Exception {
        String path = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\02.txt";
        RandomAccessFile aFile = new RandomAccessFile(path,"rw");
        FileChannel channel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(1024);

        String newData = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\02.txt";
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();
        while(buf.hasRemaining()){
            channel.write(buf);
        }
        aFile.close();
    }

    /**
     * 两个通道之间传输
     * @throws Exception
     */
    public static void trans() throws Exception {
        String path1 = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\01.txt";
        RandomAccessFile aFile1 = new RandomAccessFile(path1,"rw");
        FileChannel channelFrom = aFile1.getChannel();

        String path2 = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\02.txt";
        RandomAccessFile aFile2 = new RandomAccessFile(path2,"rw");
        FileChannel channelTo = aFile2.getChannel();

        long position = 0;
        //channelTo.transferFrom(channelFrom,position+22,channelFrom.size());
        channelFrom.transferTo(position,channelFrom.size(),channelTo);
        aFile1.close();
        aFile2.close();

    }

}
